import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import {
  Avatar,
  Button,
  Card,
  Col,
  DatePicker,
  Dropdown,
  Input,
  List,
  message,
  Modal,
  Progress,
  Radio,
  Row,
  Space,
  Table,
  Tag,
  Tooltip,
} from 'antd';
import dayjs from 'dayjs';
import type { FC } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import OperationModal from './components/OperationModal';
import type { BasicListItemDataType } from './data.d';
import { addFakeList, queryFakeList, removeFakeList, updateFakeList } from './service';
import useStyles from './style.style';
import {
  listApplyInterfaceInfoCountByPageUsingGet,
  listApplyInterfaceInfoMainMesByPageUsingGet, updateApplyStatusAndAddUserInterfaceUsingPut,
} from '@/services/api-share-backhend/applyInterfaceInfoController';
import { SortOrder } from 'antd/lib/table/interface';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search } = Input;
const Info: FC<{
  title: React.ReactNode;
  value: React.ReactNode;
  bordered?: boolean;
}> = ({ title, value, bordered }) => {
  const { styles } = useStyles();
  return (
    <div className={styles.headerInfo}>
      <span>{title}</span>
      <p>{value}</p>
      {bordered && <em />}
    </div>
  );
};

const CustomTable = ({ currentStatus }) => {
  const columns: ProColumns<API.ApplyInterfaceInfoVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInSearch: true,
      width: 50,
      valueType: 'index',
    },

    {
      title: '用户账号',
      dataIndex: 'userAccount',
      width: 90,
      valueType: 'text',
      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.userAccount}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '付款人',
      dataIndex: 'payerName',
      width: 90,
      valueType: 'text',
      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.userAccount}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '接口名',
      dataIndex: 'interfaceName',
      width: 90,
      valueType: 'text',
      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.interfaceName}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '申请数量',
      dataIndex: 'applyNum',
      width: 90,
      valueType: 'text',
      ellipsis: true,
      render: (text, record) => (
          // `title` 是在鼠标悬浮时显示的内容
          <Tooltip title={record.interfaceName}>
            <div>
              {/*正常表格显示的内容*/}
              {text}
            </div>
          </Tooltip>
      ),
    },
    {
      title: '申请理由',
      width: 120,
      dataIndex: 'reason',
      valueType: 'textarea',
      hideInSearch: true,
      ellipsis: true,
      render: (text, record) => (
        // `title` 是在鼠标悬浮时显示的内容
        <Tooltip title={record.reason}>
          <div>
            {/*正常表格显示的内容*/}
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '申请状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 50,
      valueEnum: {
        0: {
          text: '待处理',
          status: 'Default',
        },
        1: {
          text: '已通过',
          status: 'Processing',
        },
        2: {
          text: '已拒绝',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      hideInSearch: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <DatePicker
            {...rest}
            needConfirm={true}
            onOk={(value) => form.setFieldsValue({ createTime: value })}
          />
        );
      },
      width: 90,
    },
    {
      title: '操作',
      dataIndex: 'option',

      width: 90,
      valueType: 'option',
      render: (_, record) =>
        record.status === 0 ? (
          <Space>
            <Button key={'change'} onClick={() => {handleAccept(record)}}>
              通过
            </Button>

            <Button key={'offline'} style={{ color: '#F7B179' }} onClick={() => {handleRefuse(record)}}>
              拒绝
            </Button>
          </Space>
        ) : (
          <text>已处理</text>
        ),
    },
  ];
  const [loading, setLoading] = useState<boolean>(true);
  const actionRef = useRef();
  const handleAccept=async (value)=>{
    const {id,applyNum}=value
    const reqParam={
      id:id,
      applyNum:applyNum,
      status:1
    }
    try {
      const res = await updateApplyStatusAndAddUserInterfaceUsingPut(reqParam)
      if (res?.data) {
        message.success("处理成功")
        actionRef.current.reload()
      } else {
        message.error(res.message)
      }
    } catch (e) {
      message.error('服务器异常');
    }
  }
  const handleRefuse=async (value)=>{
    const {id,applyNum}=value
    const reqParam={
      id:id,
      applyNum:applyNum,
      status:2
    }
    try {
      const res = await updateApplyStatusAndAddUserInterfaceUsingPut(reqParam)
      if (res?.data) {
        message.success("处理成功")
        actionRef.current.reload()
      } else {
        message.error(res.message)
      }
    } catch (e) {
      message.error('服务器异常');
    }
  }

  useEffect(() => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }, [currentStatus]);

  return (
    <ProTable<API.ApplyInterfaceInfoVO, API.PageParams>
      actionRef={actionRef}
      rowKey="id"
      loading={loading}
      search={{
        labelWidth: 120,
      }}
      request={async (params, sort, filter) => {
        try {
          setLoading(true)
          const res = await listApplyInterfaceInfoMainMesByPageUsingGet({
            ...params,
            status: currentStatus,
          });
          if (res?.data) {
            setLoading(false)
            const ans = {
              data: res.data.records,
              success: true,
              total: res.data.total,
            };
            return ans;
          } else {
            const ans = {
              data: null,
              success: false,
              total: res.data.total,
            };
            setLoading(false)
            return ans;
          }
        } catch (e) {
          setLoading(false)
          message.error('服务器异常');
        }
      }}
      columns={columns}
    />
  );
};
export const BasicList: FC = () => {
  const { styles } = useStyles();

  const getData = async () => {
    try {
      const res = await listApplyInterfaceInfoCountByPageUsingGet();
      if (res.data === null) {
        message.error(res.message);
      } else {
        return { data: res.data };
      }
    } catch (e) {
      message.error('服务器异常');
    }
    return { data: null };
  };

  const { data, loading, mutate } = useRequest(() => {
    return getData();
  });

  // 在组件中定义一个状态来存储 applyNum、mainMes 和 weekNum
  const [applyNum, setApplyNum] = useState(0);
  const [totalNum, setTotalNum] = useState(0);
  const [weekNum, setWeekNum] = useState(0);
  const [currentStatus, setCurrentStatus] = useState<number>(0);
  useEffect(() => {
    // 当 data 发生变化时，更新 applyNum、mainMes 和 weekNum
    if (data) {
      setApplyNum(data.applyNum);
      setTotalNum(data.totalNum);
      setWeekNum(data.weekNum);
    }
  }, [data]);

  // 在这里使用 applyNum、mainMes 和 weekNum 变量

  const handleDiffStatus = (value) => {
    setCurrentStatus(value);
  };
  const extraContent = (
    <div>
      <RadioGroup defaultValue="apply" style={{ marginRight: 100 }}>
        <RadioButton
          value="apply"
          onClick={() => {
            handleDiffStatus(0);
          }}
        >
          申请中
        </RadioButton>
        <RadioButton
          value="progress"
          onClick={() => {
            handleDiffStatus(1);
          }}
        >
          已通过
        </RadioButton>

        <RadioButton
          value="refuse"
          onClick={() => {
            handleDiffStatus(2);
          }}
        >
          已拒绝
        </RadioButton>
        <RadioButton
          value="all"
          onClick={() => {
            handleDiffStatus(3);
          }}
        >
          全部
        </RadioButton>
      </RadioGroup>
    </div>
  );

  return (
    <div>
      <PageContainer>
        <div className={styles.standardList}>
          <Card bordered={false}>
            <Row>
              <Col sm={8} xs={24}>
                <Info title="待处理申请" value={`${applyNum}个任务`} bordered />
              </Col>
              <Col sm={8} xs={24}>
                <Info title="本周申请数量" value={`${weekNum}个任务`} />
              </Col>
              <Col sm={8} xs={24}>
                <Info title="总申请数量" value={`${totalNum}个任务`} />
              </Col>
            </Row>
          </Card>

          <Card
            className={styles.listCard}
            bordered={false}
            title="申请信息"
            style={{
              marginTop: 24,
            }}
            extra={extraContent}
          >
            <CustomTable currentStatus={currentStatus} />
          </Card>
        </div>
      </PageContainer>
    </div>
  );
};
export default BasicList;
